package com.carbon.system.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceUtils;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 数据库配置类
 * 用于设置正确的字符编码
 */
@Configuration
public class DatabaseConfig {

    private final DataSource dataSource;

    public DatabaseConfig(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @PostConstruct
    public void initDatabase() {
        Connection connection = null;
        try {
            connection = DataSourceUtils.getConnection(dataSource);
            // 设置字符集为utf8
            connection.createStatement().execute("SET NAMES utf8");
            connection.createStatement().execute("SET character_set_client = utf8");
            connection.createStatement().execute("SET character_set_connection = utf8");
            connection.createStatement().execute("SET character_set_results = utf8");
            System.out.println("数据库字符集已设置为utf8");
        } catch (SQLException e) {
            System.err.println("设置数据库字符集失败: " + e.getMessage());
        } finally {
            if (connection != null) {
                DataSourceUtils.releaseConnection(connection, dataSource);
            }
        }
    }
}
